package guoanmaker.provider.business.service;

import guoanmaker.provider.business.model.ProvideShop;
import guoanmaker.provider.business.model.ProvideShopFollow;
import guoanmaker.provider.business.model.ShopCommodity;
import guoanmaker.provider.business.modelnobind.ProvideShopListMove;
import guoanmaker.provider.business.repository.PersonalUserRepository;
import guoanmaker.provider.business.repository.ProvideShopFollowRepository;
import guoanmaker.provider.business.repository.ProvideShopRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.*;

/**
 * DESC:
 * Created by JTing on 2017/12/17 10:30
 */
@Service
public class ProvideShopFollowService {
    @Autowired
    private ProvideShopFollowRepository provideShopFollowRepository;

    @Autowired
    private ProvideShopRepository provideShopRepository;
    @Autowired
    private  EntityManager entityManager;
    @Autowired
    private ProvideShopServiceInterface provideShopService;
    @Autowired
    private PersonalUserRepository personalUserRepository;
    /* *
     * @Description:关注/取消关注店铺
     * @author JTing
     * @date 2017/12/17 12:57
     * @param [shopId, userId, state]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Transactional
    public Map<String,Object> followOrNotFollow(String shopId, String userId,Integer state) {

        Map<String,Object> map = new HashMap<>();
        ProvideShop ps = provideShopRepository.findOne(shopId);
        if (ps==null) {
            map.put("error", "shop does not exist");
            return map;
        }
        if (state!=0 && state!=1) {
            map.put("error", "state is invalid");
            return map;
        }
        ProvideShopFollow sf = provideShopFollowRepository.findShopFollow(shopId,userId);
        if (sf == null) {
            //first follow
            ProvideShopFollow provideShopFollow = new ProvideShopFollow();
            provideShopFollow.setState(state);
            provideShopFollow.setUserId(userId);
            provideShopFollow.setStateTime(new Date());

            ps.setFollowNum(ps.getFollowNum()+1);
            provideShopRepository.save(ps);

            provideShopFollow.setProvideShop(ps);
            provideShopFollowRepository.save(provideShopFollow);

        }
        if (sf != null) {
            if (state==0 &&sf.getState()==1) {
                ps.setFollowNum(ps.getFollowNum()-1);
            }
            if (state==1 &&sf.getState()==0) {
                ps.setFollowNum(ps.getFollowNum()+1);
            }
            if (ps.getFollowNum()<0L) {
                ps.setFollowNum(0L);
            }
            provideShopRepository.save(ps);
            sf.setState(state);
            sf.setStateTime(new Date());
            provideShopFollowRepository.save(sf);
        }
        map.put("followNum", ps.getFollowNum());
        return map;
    }
    /* *
     * @Description:获取用户关注的店铺列表
     * @author JTing  
     * @date 2017/12/17 12:56  
     * @param [userId, page, pageSize]  
     * @return java.util.Map<java.lang.String,java.lang.Object>  
     */  
    public Map<String,Object> userShopFollowList(String userId, Integer page, Integer pageSize) {

        HashMap<String, Object> map = new HashMap<>();
        if (userId==null || personalUserRepository.findOne(userId)==null) {
            map.put("error", "there is no user");
            return map;
        }
        String jpql="select new guoanmaker.provider.business.modelnobind.ProvideShopListMove(pb.id,ps.id,pb.businessName,pb.companyLogo,ps.followNum,ps.state,pb.introduce) " +
                "from ProvideShopFollow psf left join psf.provideShop ps " +
                "left join ps.providerBusiness pb where psf.userId='"+userId+"' and psf.state=1 order by psf.stateTime desc";
        Query query = entityManager.createQuery(jpql);
        List<ProvideShopListMove> resultLists = query.getResultList();
        map.put("total", resultLists.size());
        if (page ==null || pageSize==null) {
            map.put("result", resultLists);
        }
        if (page != null && pageSize != null) {
            query.setFirstResult(page * pageSize);
            query.setMaxResults(pageSize);
            resultLists = query.getResultList();
            map.put("result", resultLists);
        }
        //为业务类添加score字段
        for (ProvideShopListMove pslm :
                resultLists) {
            pslm.setScore(provideShopService.getProvideShopScore(pslm.getBusinessId()));
        }
        return map;
    }


    public Map<String,Object> userShopFollowListForPc(String userId, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        if (userId==null || personalUserRepository.findOne(userId)==null) {
            map.put("error", "there is no user");
            return map;
        }
        map = userShopFollowList(userId, page, pageSize);
        List<ProvideShopListMove> resultLists  = (List<ProvideShopListMove>) map.get("result");
        //为每个店铺添加2个商品
        for (ProvideShopListMove p: resultLists
             ) {
            String businessId = p.getBusinessId();
            String sql = "select t.id,t.commodity_code,t.commodity_name,t.commodity_smallimage,t.final_price,t.code from " +
                    "(select id ,commodity_code,commodity_name, commodity_smallimage, final_price,release_time ,business_id,'0' as code from t_provide_commodity where  is_territory_restriction='2'  and type <>'4' and commodity_state=2  " +
                    "union all (select a.id,a.commodity_code,a.commodity_name ,a.commodity_smallimage,b.final_price ,a.release_time ,a.business_id,c.code from " +
                    "t_provide_commodity a ,(select final_price,commodity_id,city_id ,count(commodity_id) from t_provide_commodity_service_range group by commodity_id ) b ,t_provide_city c " +
                    "where b.city_id=c.id   and a.id= b.commodity_id and a.is_territory_restriction='1' and a.commodity_state=2 and a.type <>'4' ))t  where t.business_id='"+businessId+"' order by t.release_time desc   limit 2";
            Query nativeQuery = entityManager.createNativeQuery(sql);
            List resultList = nativeQuery.getResultList();
            ArrayList<ShopCommodity> shopCommodities = new ArrayList<>();
            for (Object row : resultList
                 ) {
                Object[] cells= (Object[]) row;
                shopCommodities.add(new ShopCommodity(cells[0].toString(), cells[1].toString(), cells[2].toString(), cells[3].toString(), Double.parseDouble(cells[4].toString()),cells[5].toString()));
            }

            p.setShopCommodities(shopCommodities);
        }

        return map;
    }
    public Map<String,Object> judgeUserIsFollow(String userId, String shopId) {
        Map<String, Object> map = new HashMap<>();
        if (userId==null) {
            map.put("isfollow","用户不存在");
        }
        Query nativeQuery = entityManager.createNativeQuery("select count(1) from t_provide_shop_follow where state=1 and user_id='" + userId + "' and shop_id='" + shopId + "'");
        List resultList = nativeQuery.getResultList();
        if (!resultList.get(0).toString().equals("0")) {
            map.put("isfollow", 1);
        } else {
            map.put("isfollow", -1);
        }
        return map;
    }
}
